<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.2">
  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/icon.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/icon.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/icon.png">
  <link rel="mask-icon" href="/blog/images/icon.svg" color="#222">

<link rel="stylesheet" href="/blog/css/main.css">


<link rel="stylesheet" href="/blog/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"bgape002.gitee.io","root":"/blog/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"mac"},"back2top":{"enable":true,"sidebar":false,"scrollpercent":true},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="IO多路复用能够阻塞等待，非忙轮询装填，不浪费CPU等资源，也能同一时刻监听多个IO请求的机制。  IO 多路复用是一种同步IO模型，实现一个线程可以监视多个文件句柄； 一旦某个文件句柄就绪，就能够通知应用程序进行相应的读写操作； 没有文件句柄就绪就会阻塞应用程序，交出CPU。   多路是指网络连接，复用指的是同一个线程">
<meta property="og:type" content="article">
<meta property="og:title" content="IO多路复用">
<meta property="og:url" content="https://bgape002.gitee.io/2022/07/07/IO%E5%A4%9A%E8%B7%AF%E5%A4%8D%E7%94%A8/index.html">
<meta property="og:site_name" content="bgape002">
<meta property="og:description" content="IO多路复用能够阻塞等待，非忙轮询装填，不浪费CPU等资源，也能同一时刻监听多个IO请求的机制。  IO 多路复用是一种同步IO模型，实现一个线程可以监视多个文件句柄； 一旦某个文件句柄就绪，就能够通知应用程序进行相应的读写操作； 没有文件句柄就绪就会阻塞应用程序，交出CPU。   多路是指网络连接，复用指的是同一个线程">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://bgape002.gitee.io/blog/images/blockingIO.png">
<meta property="og:image" content="https://bgape002.gitee.io/blog/images/unblockingIO.png">
<meta property="og:image" content="https://bgape002.gitee.io/blog/images/IOmultiplexing.png">
<meta property="og:image" content="https://bgape002.gitee.io/blog/images/signalDrivenIO.png">
<meta property="og:image" content="https://bgape002.gitee.io/blog/images/asynchronousIO.png">
<meta property="article:published_time" content="2022-07-07T06:06:39.000Z">
<meta property="article:modified_time" content="2022-08-04T09:54:25.566Z">
<meta property="article:author" content="bgape002">
<meta property="article:tag" content="io多路复用">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://bgape002.gitee.io/blog/images/blockingIO.png">

<link rel="canonical" href="https://bgape002.gitee.io/2022/07/07/IO%E5%A4%9A%E8%B7%AF%E5%A4%8D%E7%94%A8/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>IO多路复用 | bgape002</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/blog/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">bgape002</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">淡泊明志，宁静致远</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/blog/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/blog/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">66</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/blog/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">27</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blog/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">61</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://bgape002.gitee.io/2022/07/07/IO%E5%A4%9A%E8%B7%AF%E5%A4%8D%E7%94%A8/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/head.png">
      <meta itemprop="name" content="bgape002">
      <meta itemprop="description" content="mail: bgape002@163.com">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="bgape002">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          IO多路复用
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2022-07-07 14:06:39" itemprop="dateCreated datePublished" datetime="2022-07-07T14:06:39+08:00">2022-07-07</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2022-08-04 17:54:25" itemprop="dateModified" datetime="2022-08-04T17:54:25+08:00">2022-08-04</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/IO/" itemprop="url" rel="index"><span itemprop="name">IO</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/blog/2022/07/07/IO%E5%A4%9A%E8%B7%AF%E5%A4%8D%E7%94%A8/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/blog/2022/07/07/IO%E5%A4%9A%E8%B7%AF%E5%A4%8D%E7%94%A8/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="IO多路复用"><a href="#IO多路复用" class="headerlink" title="IO多路复用"></a>IO多路复用</h2><p><strong>能够阻塞等待，非忙轮询装填，不浪费CPU等资源，也能同一时刻监听多个IO请求的机制。</strong></p>
<ul>
<li>IO 多路复用是一种同步IO模型，实现一个线程可以监视多个文件句柄；</li>
<li>一旦某个文件句柄就绪，就能够通知应用程序进行相应的读写操作；</li>
<li>没有文件句柄就绪就会阻塞应用程序，交出CPU。</li>
</ul>
<blockquote>
<p>多路是指网络连接，复用指的是同一个线程</p>
</blockquote>
<span id="more"></span>

<h3 id="select机制"><a href="#select机制" class="headerlink" title="select机制"></a>select机制</h3><p>客户端操作服务器时就会产生这<strong>三种文件描述符(简称fd)：writefds(写)、readfds(读)、和exceptfds(异常)<strong>。select会</strong>阻塞住监视3类文件描述符</strong>，等有数据、可读、可写、出异常 或超时、就会返回；返回后通过遍历fdset整个数组来找到就绪的描述符fd，然后进行对应的IO操作。</p>
<ul>
<li>优点：<br>　　几乎在所有的平台上支持，跨平台支持性好</li>
<li>缺点：<ul>
<li>由于是采用轮询方式全盘扫描，会随着文件描述符FD数量增多而性能下降。</li>
<li>每次调用 select()，需要把 fd 集合从用户态拷贝到内核态，并进行遍历(消息传递都是从内核到用户空间)</li>
<li>默认单个进程打开的FD有限制是1024个，可修改宏定义，但是效率仍然慢。</li>
</ul>
</li>
</ul>
<h3 id="poll机制"><a href="#poll机制" class="headerlink" title="poll机制"></a>poll机制</h3><ul>
<li>基本原理与select一致，只是没有最大文件描述符限制，因为采用的是链表存储fd。</li>
</ul>
<h3 id="epoll机制"><a href="#epoll机制" class="headerlink" title="epoll机制"></a>epoll机制</h3><ul>
<li><p>epoll之所以高性能是得益于它的三个函数</p>
<ul>
<li>epoll_create()系统启动时，在Linux内核里面申请一个B+树结构文件系统，返回epoll对象，也是一个fd</li>
<li>epoll_ctl() 每新建一个连接，都通过该函数操作epoll对象，在这个对象里面修改添加删除对应的链接fd, 绑定一个callback函数。</li>
<li>epoll_wait() 轮训所有的callback集合，并完成对应的IO操作</li>
</ul>
</li>
<li><p>优点：<br>　　- 没fd这个限制，所支持的FD上限是操作系统的最大文件句柄数，1G内存大概支持10万个句柄</p>
<ul>
<li>效率提高，使用回调通知而不是轮询的方式，不会随着FD数目的增加效率下降</li>
<li>内核和用户空间mmap同一块内存实现</li>
</ul>
</li>
</ul>
<h3 id="同步-amp-异步"><a href="#同步-amp-异步" class="headerlink" title="同步&amp;异步"></a>同步&amp;异步</h3><p>同步和异步描述的是<strong>消息通信的机制</strong>。</p>
<ul>
<li><p>同步</p>
<p><strong>代码调用IO操作时，必须等待IO操作完成才返回的调用方式。</strong>当一个request发送出去以后，会得到一个response，这整个过程就是一个同步调用的过程。哪怕response为空，或者response的返回特别快，但是针对这一次请求而言就是一个同步的调用。</p>
</li>
<li><p>异步</p>
<p><strong>代码调用IO操作时，不必等待IO操作完成才返回的调用方式。</strong>当一个request发送出去以后，没有得到想要的response，而是通过后面的callback、状态或者通知的方式获得结果。可以这么理解，对于异步请求分两步：</p>
<p><code>1.</code>调用方发送request没有返回对应的response（可能是一个空的response）；</p>
<p><code>2.</code>服务提供方将response处理完成以后通过callback的方式通知调用方。</p>
<blockquote>
<p>对于1. 而言是同步操作（调用方请求服务方），对于2. 而言也是同步操作（服务方回调调用方）。从请求的目的（调用方发送一个request，希望获得对应的response）来看，这两个步骤拆分开来没有任何意义；而<strong>需要结合起来看，这整个过程就是一次异步请求</strong>。</p>
<p><strong>异步请求有一个最典型的特点：需要callback、状态或者通知的方式来告知调用方结果。</strong></p>
</blockquote>
</li>
</ul>
<h3 id="阻塞-amp-非阻塞"><a href="#阻塞-amp-非阻塞" class="headerlink" title="阻塞&amp;非阻塞"></a>阻塞&amp;非阻塞</h3><p>阻塞和非阻塞描述的是程序在等待调用结果（消息，返回值）时的状态。<strong>函数调用的机制</strong>。</p>
<ul>
<li><p>阻塞</p>
<p>阻塞调用是指调用方发出request的线程因为某种原因（如：等待系统资源）<strong>被服务方挂起</strong>，当服务方得到response后就唤醒挂起线程，并将response返回给调用方。</p>
</li>
<li><p>非阻塞</p>
<p>非阻塞调用是指调用方发出request的线程在没有等到结果时<strong>不会被挂起</strong>，直到得到response后才返回。</p>
</li>
</ul>
<p>阻塞和非阻塞最大的<strong>区别是在调用方线程是否会被挂起</strong>。</p>
<!-- more -->

<h3 id="Unix系统下的五种I-O模型"><a href="#Unix系统下的五种I-O模型" class="headerlink" title="Unix系统下的五种I/O模型"></a>Unix系统下的五种I/O模型</h3><ul>
<li><p>阻塞式I/O</p>
<p><img src="/blog/images/blockingIO.png" alt="."></p>
</li>
<li><p>非阻塞式I/O</p>
<p><img src="/blog/images/unblockingIO.png" alt="."></p>
</li>
<li><p>I/O复用</p>
<p><img src="/blog/images/IOmultiplexing.png" alt="."></p>
</li>
<li><p>信号驱动式I/O</p>
<p><img src="/blog/images/signalDrivenIO.png" alt="."></p>
</li>
<li><p>异步I/O</p>
<p><img src="/blog/images/asynchronousIO.png" alt="."></p>
</li>
</ul>
<h3 id="select-回调-事件循环实现IO多路复用"><a href="#select-回调-事件循环实现IO多路复用" class="headerlink" title="select+回调+事件循环实现IO多路复用"></a>select+回调+事件循环实现IO多路复用</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> socket</span><br><span class="line"><span class="keyword">from</span> urllib.parse <span class="keyword">import</span> urlparse</span><br><span class="line"><span class="keyword">from</span> selectors <span class="keyword">import</span> DefaultSelector, EVENT_WRITE, EVENT_READ</span><br><span class="line"><span class="keyword">import</span> time</span><br><span class="line"></span><br><span class="line">selector = DefaultSelector()</span><br><span class="line">urls = []</span><br><span class="line">STOP = <span class="literal">False</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Fetcher</span>(<span class="title class_ inherited__">object</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self</span>):</span><br><span class="line">        self.data = <span class="string">b&quot;&quot;</span></span><br><span class="line">        self.host = <span class="literal">None</span></span><br><span class="line">        self.path = <span class="literal">None</span></span><br><span class="line">        self.client = <span class="literal">None</span></span><br><span class="line">        self.spider_url = <span class="literal">None</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">connected</span>(<span class="params">self, key</span>):</span><br><span class="line">        selector.unregister(key.fd)</span><br><span class="line">        self.client.send(<span class="string">&quot;GET &#123;&#125; HTTP/1.1\r\nHost:&#123;&#125;\r\nConnection:close\r\n\r\n&quot;</span>.<span class="built_in">format</span>(self.path, self.host).encode(<span class="string">&quot;utf8&quot;</span>))</span><br><span class="line">        selector.register(self.client.fileno(), EVENT_READ, self.readable)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">readable</span>(<span class="params">self, key</span>):</span><br><span class="line">        d = self.client.recv(<span class="number">1024</span>)</span><br><span class="line">        <span class="keyword">if</span> d:</span><br><span class="line">            self.data += d</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            selector.unregister(key.fd)</span><br><span class="line">            data = self.data.decode(<span class="string">&quot;utf8&quot;</span>)</span><br><span class="line">            html_data = data.split(<span class="string">&quot;\r\n\r\n&quot;</span>)[<span class="number">1</span>]</span><br><span class="line">            <span class="built_in">print</span>(html_data)</span><br><span class="line">            self.client.close()</span><br><span class="line">            urls.remove(self.spider_url)</span><br><span class="line">            <span class="keyword">if</span> <span class="keyword">not</span> urls:</span><br><span class="line">                <span class="keyword">global</span> STOP</span><br><span class="line">                STOP = <span class="literal">True</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">get_url</span>(<span class="params">self, url</span>):</span><br><span class="line">        self.spider_url = url</span><br><span class="line">        url = urlparse(url)</span><br><span class="line">        self.host = url.netloc</span><br><span class="line">        self.path = url.path</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> self.path == <span class="string">&quot;&quot;</span>:</span><br><span class="line">            self.path = <span class="string">&quot;/&quot;</span></span><br><span class="line"></span><br><span class="line">        <span class="comment"># 建立socket连接</span></span><br><span class="line">        self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)</span><br><span class="line">        self.client.setblocking(<span class="literal">False</span>)</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span>:</span><br><span class="line">            self.client.connect((self.host, <span class="number">80</span>))</span><br><span class="line">        <span class="keyword">except</span> BlockingIOError <span class="keyword">as</span> e:</span><br><span class="line">            <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line">        <span class="comment"># 注册</span></span><br><span class="line">        selector.register(self.client.fileno(), EVENT_WRITE, self.connected)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">loop</span>():</span><br><span class="line">    <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">    事件循环，不停的请求socket的状态并调用对应的回调函数</span></span><br><span class="line"><span class="string">    模式： 回调+事件循环+select/poll/epoll</span></span><br><span class="line"><span class="string">    &quot;&quot;&quot;</span></span><br><span class="line">    <span class="comment"># 1. selector本身是不支持register模式的</span></span><br><span class="line">    <span class="comment"># 2. socket状态变化后的回调是由程序员完成的</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># while True:</span></span><br><span class="line">    <span class="keyword">while</span> <span class="keyword">not</span> STOP:</span><br><span class="line">        ready = selector.select()</span><br><span class="line">        <span class="keyword">for</span> key, mask <span class="keyword">in</span> ready:</span><br><span class="line">            call_back = key.data</span><br><span class="line">            call_back(key)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&quot;__main__&quot;</span>:</span><br><span class="line">    <span class="comment"># fetcher = Fetcher()</span></span><br><span class="line">    start = time.time()</span><br><span class="line">    <span class="keyword">for</span> seq <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">20</span>):</span><br><span class="line">        url = <span class="string">&quot;http://shop.projectsedu.com/goods/&#123;&#125;/&quot;</span>.<span class="built_in">format</span>(seq)</span><br><span class="line">        urls.append(url)</span><br><span class="line">        fetcher = Fetcher()</span><br><span class="line">        fetcher.get_url(url)</span><br><span class="line">    loop()</span><br><span class="line">    <span class="built_in">print</span>(time.time()-start)</span><br></pre></td></tr></table></figure>







<h3 id="参考链接"><a href="#参考链接" class="headerlink" title="参考链接"></a>参考链接</h3><font size=2>

<p>[1] <a target="_blank" rel="noopener" href="https://blog.csdn.net/junaozun/article/details/120169537">IO多路复用机制</a></p>
<p>[2] <a target="_blank" rel="noopener" href="https://blog.csdn.net/chenwiehuang/article/details/105296691?spm=1001.2101.3001.6661.1&utm_medium=distribute.pc_relevant_t0.none-task-blog-2~default~CTRLIST~default-1-105296691-blog-120169537.pc_relevant_multi_platform_whitelistv1&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-2~default~CTRLIST~default-1-105296691-blog-120169537.pc_relevant_multi_platform_whitelistv1&utm_relevant_index=1">Java IO多路复用机制详解</a></p>
<p>[3] <a target="_blank" rel="noopener" href="https://www.bilibili.com/video/BV1QY4y147K5?p=79&vd_source=5f03bdbb9a8460c7ae08f9cdea23577b">Python高级核心技术97讲</a></p>
<p>[4] <a target="_blank" rel="noopener" href="https://blog.csdn.net/qq_41607336/article/details/118705446">同步异步/阻塞非阻塞</a></p>
</font>


    </div>

    
    
    

      <footer class="post-footer">
          
          <div class="post-tags">
              <a href="/blog/tags/io%E5%A4%9A%E8%B7%AF%E5%A4%8D%E7%94%A8/" rel="tag"><i class="fa fa-tag"></i> io多路复用</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blog/2022/07/06/%E7%BC%96%E7%A8%8B%E4%B8%AD%E4%B8%80%E4%BA%9B%E5%B0%8F%E7%9A%84%E6%B3%A8%E6%84%8F%E7%9A%84%E7%82%B9/" rel="prev" title="编程中一些小的注意的点">
      <i class="fa fa-chevron-left"></i> 编程中一些小的注意的点
    </a></div>
      <div class="post-nav-item">
    <a href="/blog/2022/07/07/%E7%94%9F%E6%88%90%E5%99%A8%E8%BF%9B%E9%98%B6/" rel="next" title="生成器进阶">
      生成器进阶 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>


        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#IO%E5%A4%9A%E8%B7%AF%E5%A4%8D%E7%94%A8"><span class="nav-number">1.</span> <span class="nav-text">IO多路复用</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#select%E6%9C%BA%E5%88%B6"><span class="nav-number">1.1.</span> <span class="nav-text">select机制</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#poll%E6%9C%BA%E5%88%B6"><span class="nav-number">1.2.</span> <span class="nav-text">poll机制</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#epoll%E6%9C%BA%E5%88%B6"><span class="nav-number">1.3.</span> <span class="nav-text">epoll机制</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%90%8C%E6%AD%A5-amp-%E5%BC%82%E6%AD%A5"><span class="nav-number">1.4.</span> <span class="nav-text">同步&amp;异步</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E9%98%BB%E5%A1%9E-amp-%E9%9D%9E%E9%98%BB%E5%A1%9E"><span class="nav-number">1.5.</span> <span class="nav-text">阻塞&amp;非阻塞</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Unix%E7%B3%BB%E7%BB%9F%E4%B8%8B%E7%9A%84%E4%BA%94%E7%A7%8DI-O%E6%A8%A1%E5%9E%8B"><span class="nav-number">1.6.</span> <span class="nav-text">Unix系统下的五种I&#x2F;O模型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#select-%E5%9B%9E%E8%B0%83-%E4%BA%8B%E4%BB%B6%E5%BE%AA%E7%8E%AF%E5%AE%9E%E7%8E%B0IO%E5%A4%9A%E8%B7%AF%E5%A4%8D%E7%94%A8"><span class="nav-number">1.7.</span> <span class="nav-text">select+回调+事件循环实现IO多路复用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8F%82%E8%80%83%E9%93%BE%E6%8E%A5"><span class="nav-number">1.8.</span> <span class="nav-text">参考链接</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="bgape002"
      src="/blog/images/head.png">
  <p class="site-author-name" itemprop="name">bgape002</p>
  <div class="site-description" itemprop="description">mail: bgape002@163.com</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">61</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/blog/categories/">
          
        <span class="site-state-item-count">27</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/blog/tags/">
          
        <span class="site-state-item-count">66</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2021 – 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">bgape002</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/blog/lib/anime.min.js"></script>
  <script src="/blog/lib/velocity/velocity.min.js"></script>
  <script src="/blog/lib/velocity/velocity.ui.min.js"></script>

<script src="/blog/js/utils.js"></script>

<script src="/blog/js/motion.js"></script>


<script src="/blog/js/schemes/pisces.js"></script>


<script src="/blog/js/next-boot.js"></script>




  




  
<script src="/blog/js/local-search.js"></script>











<script>
if (document.querySelectorAll('pre.mermaid').length) {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js', () => {
    mermaid.initialize({
      theme    : 'forest',
      logLevel : 3,
      flowchart: { curve     : 'linear' },
      gantt    : { axisFormat: '%m/%d/%Y' },
      sequence : { actorMargin: 50 }
    });
  }, window.mermaid);
}
</script>


  

  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : false,
      appId      : 'szhBf0Qamzsowubi1WnkXmUj-gzGzoHsz',
      appKey     : 'WpwxoK0fVJHvhzWwakr9vbpA',
      placeholder: "Just go go",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : false,
      lang       : '' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

</body>
</html>
